import { createSlice } from '@reduxjs/toolkit'
import { realm, schemaName } from "../../utils/schema"
import httpApi from "../../api"
import { formatFriendMsg, formatGroupMsg } from "../../utils/formatFriendMsg"

const initialState = {
    token: "",
    userInfo: {},
    userInfoList: [],
    friendList: [],
    groupList: [],
    friendMsg: [],
    groupMsg: [],
    friendApplyMsg: [],
    personalFriendPageMsgItem: {},
    cuurentPersonalFriendPageInfo: {},
    isLogin: false,
    isLoadingLoadFrom: false
}
export const appSlice = createSlice({
    name: 'app',
    initialState,
    reducers: {
        setLogin: (state, action) => {
            state.friendList = []
            state.groupList = []
            state.friendMsg = []
            state.groupMsg = []
            state.friendApplyMsg = []
            state.personalFriendPageMsgItem = {}
            state.cuurentPersonalFriendPageInfo = {}
        },
        SetToken: (state, action) => {
            state.token = action.payload
        },
        SetUserInfo: (state, action) => {
            state.userInfo = action.payload
        },
        SetUserInfoList: (state, action) => {
            state.userInfoList = action.payload
        },
        SetFriendList: (state, action) => {
            state.friendList = action.payload || []
        },
        SetGroupList: (state, action) => {
            state.groupList = action.payload || []
        },
        SetFriendMsg: (state, action) => {
            state.friendMsg = action.payload
        },
        SetGroupMsg: (state, action) => {
            state.groupMsg = action.payload
        },
        SetFriendApplyMsgMsg: (state, action) => {
            state.friendApplyMsg = action.payload
        },
        SetPersonalFriendPageMsgItem: (state, action) => {
            state.personalFriendPageMsgItem = action.payload
        },
        SetCuurentPersonalFriendPageInfo: (state, action) => {
            state.cuurentPersonalFriendPageInfo = action.payload
        },
        setIsLogin: (state, action) => {
            state.isLogin = action.payload
        },
        setIsLoadingLoadFrom: (state, action) => {
            state.isLoadingLoadFrom = action.payload
        },
    },
})

export const {
    setLogin,
    SetToken,
    SetUserInfo,
    SetUserInfoList,
    SetFriendList,
    SetGroupList,
    SetFriendMsg,
    SetGroupMsg,
    SetFriendApplyMsgMsg,
    SetNewFriendMsg,
    SetPersonalFriendPageMsgItem,
    SetCuurentPersonalFriendPageInfo,
    setIsLogin
} = appSlice.actions

export const asyncRegister = (sign) => async (dispatch) => {
    try {
        const params = {
            nickname: "BNB-1",
            signature: sign,
            message: httpApi.message,
            profilePhoto: httpApi.defaultAvatar
        };
        const res = await httpApi.register(params)
        if (res.code == 20) {
            const userInfoList = realm.objects(schemaName.UserInfoList)
            const userInfoListFiltered = userInfoList.filtered(`Id == ${res.data.UserInfo.Id}`)
            const userInfo = realm.objects(schemaName.UserInfo)
            if (userInfoList.length == 0 || userInfoListFiltered[0]?.Id == userInfo[0]?.Id) dispatch(SetToken(res.data.Token));
            if (userInfoList.length == 0 || userInfoListFiltered[0]?.Id == userInfo[0]?.Id) dispatch(SetUserInfo(res.data.UserInfo));
            realm.write(() => {
                if (userInfoList.length == 0 || userInfoListFiltered[0]?.Id == userInfo[0]?.Id) realm.create(schemaName.UserInfo, { ...res.data.UserInfo, Token: res.data.Token }, true);
                realm.create(schemaName.UserInfoList, { ...res.data.UserInfo, Token: res.data.Token }, true);
            })
            dispatch(SetUserInfoList(JSON.parse(JSON.stringify(userInfoList))));
        }
        return res
    } catch (error) {
        return error
    }
}

export const asyncLogin = (sign) => async (dispatch) => {
    try {
        const params = {
            signature: sign,
            message: httpApi.message
        };
        const res = await httpApi.login(params)
        if (res.code == 20) {
            const userInfoList = realm.objects(schemaName.UserInfoList)
            const userInfoListFiltered = userInfoList.filtered(`Id == ${res.data.UserInfo.Id}`)
            const userInfo = realm.objects(schemaName.UserInfo)
            if (userInfoList.length == 0 || userInfoListFiltered[0]?.Id == userInfo[0]?.Id) dispatch(SetToken(res.data.Token));
            if (userInfoList.length == 0 || userInfoListFiltered[0]?.Id == userInfo[0]?.Id) dispatch(SetUserInfo(res.data.UserInfo));
            realm.write(() => {
                if (userInfoList.length == 0 || userInfoListFiltered[0]?.Id == userInfo[0]?.Id) realm.create(schemaName.UserInfo, { ...res.data.UserInfo, Token: res.data.Token }, true);
                realm.create(schemaName.UserInfoList, { ...res.data.UserInfo, Token: res.data.Token }, true);
            })
            dispatch(SetUserInfoList(JSON.parse(JSON.stringify(userInfoList))));
        }
        return res
    } catch (error) {
        return error
    }
}

export const asyncGetUserInfo = () => async (dispatch) => {
    try {
        const res = await httpApi.getUserInfo()
        if (res.code == 20) {
            dispatch(SetUserInfo(res.data.UserInfo));
            realm.write(() => {
                realm.create(schemaName.UserInfo, res.data.UserInfo, true);
                realm.create(schemaName.UserInfoList, res.data.UserInfo, true);
            })
            const UserInfoList = realm.objects(schemaName.UserInfoList)
            dispatch(SetUserInfo(res.data.UserInfo));
            dispatch(SetUserInfoList(JSON.parse(JSON.stringify(UserInfoList))));

        }
        return res
    } catch (error) {
        return error
    }
}


export const asyncGetFriendList = (UserId) => async (dispatch) => {
    try {
        const res = await httpApi.getFriendList()
        let FriendList = realm.objects(schemaName.FriendList).filtered(`UserId == ${UserId}`)
        realm.write(() => {
            // realm.delete(FriendList);
            for (let index = 0; index < res.data.FriendList?.length; index++) {
                const element = res.data.FriendList[index];
                realm.create(schemaName.FriendList, { ...element, UserId, State: 1 }, true);
            }
        })
        dispatch(SetFriendList(JSON.parse(JSON.stringify(FriendList))));
        return res.data
    } catch (error) {

    }
};

export const asyncGetGroupList = (UserId) => async (dispatch) => {
    try {
        const res = await httpApi.getGroupList()
        let GroupList = realm.objects(schemaName.GroupList).filtered(`UserId == ${UserId}`)
        realm.write(() => {
            // realm.delete(GroupList);
            for (let index = 0; index < res.data.GroupList?.length; index++) {
                const element = res.data.GroupList[index];
                realm.create(schemaName.GroupList, { ...element, UserId, State: 1 }, true);
            }
        })
        dispatch(SetGroupList(JSON.parse(JSON.stringify(GroupList))));
        return res.data.GroupList
    } catch (error) {

    }
};



export const asyncGetFriendMsg = (seq, num) => async (dispatch) => {
    const res = await httpApi.getFriendMsg({ seq, num })
    dispatch(SetFriendMsg(res.data.Msgs || [])) //?
    return res.data.Msgs || []
};

export const syncPageGetFriendMsg = (item) => (dispatch) => {
    dispatch(SetPersonalFriendPageMsgItem(item || {}))
};

export const syncPageGetFriendMsgSeq = (id, UserId) => (dispatch) => {
    let MsgLis = realm.objects(schemaName.FriendMsgLis);
    let Unread = JSON.parse(JSON.stringify(MsgLis.filtered(`F == ${id} and UserId == ${UserId} and Unread == 1`)))
    realm.write(() => {
        for (let index = 0; index < Unread.length; index++) {
            const element = Unread[index];
            realm.create(schemaName.FriendMsgLis, { ...element, Unread: 0 }, true);
        }
    })
    dispatch(SetFriendMsg(formatFriendMsg() || []))
};

export const syncPageGetGroupMsgSeq = (id, UserId) => (dispatch) => {
    let GroupMsgLis = realm.objects(schemaName.GroupMsgLis);
    let Unread = JSON.parse(JSON.stringify(GroupMsgLis.filtered(`G == ${id} and UserId == ${UserId} and Unread == 1 and MT != 61`)))
    realm.write(() => {
        for (let index = 0; index < Unread.length; index++) {
            const element = Unread[index];
            realm.create(schemaName.GroupMsgLis, { ...element, Unread: 0 }, true);
        }
    })
    dispatch(SetGroupMsg(formatGroupMsg() || []))
};





export default appSlice.reducer